<template>
  <el-form label-width="80px"  >
    <el-form-item label="SPU名称">
      <el-input placeholder="SPU名称" v-model="newSpuInfo.spuName"></el-input>
    </el-form-item>

    <el-form-item label="品牌">
      <!-- 进来的数据中tmid和这里value意义对应 -->
      <el-select   placeholder="请选择" v-model="(newSpuInfo.tmId as number)">
        <!-- 这里显示的数据需要 -->
        <el-option v-for="tm in trademarkData" :key="tm.id" :value="tm.id" :label="tm.tmName"></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="SPU描述">
      <el-input placeholder="SPU描述" type="textarea" rows="4" v-model="newSpuInfo.description"></el-input>
    </el-form-item>

    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="tmImgData as UploadUserFile[]"
        :action="`${baseUrl}/admin/product/upload`"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select :placeholder="`还有${newSalesAttrData.length}个未选择`"  v-model="tempSalesAttr" >

        <el-option v-for="sale in newSalesAttrData" :key="sale.id" :value="`${sale.id}:${sale.name}`" :label="sale.name"></el-option>
      </el-select>
      <el-button type="primary" size="default" @click="AddNewSalesValue">添加销售属性</el-button>
    </el-form-item>
       <!-- 销售属性列表 -->
    <el-form-item >
      <el-table  border stripe style="margin-bottom:20px" :data="salesAttrList">
        <el-table-column type="index" width="80" label="序号" align="center" />
        <el-table-column label="属性名" prop="saleAttrName"> </el-table-column>
        <el-table-column label="属性值名称列表" prop="spuSaleAttrValueList">
          <template #default="{row,$index}">
            <!-- @close="handleClose(tag)" -->
            <el-tag
              v-for="tag in row.spuSaleAttrValueList"
              :key="tag.id"
              class="mx-1"
              closable
              :disable-transitions="true"
              @close="row.spuSaleAttrValueList.splice($index,1)"
              >
              
              {{tag.saleAttrValueName}}
            </el-tag>
            <!-- v-if="inputVisible" v-model="inputValue"  @keyup.enter="handleInputConfirm"
              -->
            <el-input
              ref="InputRef"
              class="ml-1 w-20"
              size="small"
              v-if="row.isEdit"
              @blur="handleInputConfirm(row)"
              v-model="row.inputValue"
            
            />
            <el-button v-else 
            class="button-new-tag ml-1" 
            size="small" 
            type="primary" 
            @click="addSalesValue(row)"
            
            >
              + 点击新增属性
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <template #default="{$index}">
             <el-button type="danger" size="small" @click="salesAttrList.splice($index,1)" icon="ele-Delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="default" @click="saveSpuData">保存</el-button>
      <el-button type="default" size="default" @click="emit('changeShowState',0)">取消</el-button>
    </el-form-item>

  </el-form>
  
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "SpuForm",
});
</script>

<script setup lang="ts">
  import { computed, onMounted, ref,nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import { requestBaseSaleAttrList, requestSaveSpuInfo, requestSpuImgList, requestSpuSaleAttrList, requestUpdateSpuInfo, type BaseSaleAttrListType, type SpuImgListType, type SpuInfoType, type SpuSaleAttrItemType, type SpuSaleAttrListType } from '@/api/spu';
import { requestTmList, type TmListType, type TradeRecordsItemType } from '@/api/tradeMark';

const baseUrl = import.meta.env.VITE_API_URL
//切换显示状态
const emit = defineEmits<{
  (event:'changeShowState',val:number):void;
}>()

//接收由修改状态传来的数据
const props = defineProps<{
  newSpuInfo:SpuInfoType
}>()

// 图片上传逻辑
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}


//根据新增和修改，分别请求对应需要的数据逻辑
//创建四个参数接收
//品牌数据
const trademarkData = ref<TmListType[]>([])
//图片数据
const tmImgData = ref<SpuImgListType>([])
//销售属性数据
const salesAttrData = ref<BaseSaleAttrListType>([])
//销售属性列表数据
const salesAttrList = ref<SpuSaleAttrListType>([])

//创建请求函数
const getNeedData = async()=>{
  //判断有没有进入组件中有没有id
  if(!props.newSpuInfo.id){
    //如果没有id，则说明是新增模式
    //只请求
    const result1 = await requestTmList()
    trademarkData.value = result1
    const result2 = await requestBaseSaleAttrList()
    salesAttrData.value = result2
  }else{
    const result1 = await requestTmList()
    trademarkData.value = result1
    const result2 = await requestBaseSaleAttrList()
    salesAttrData.value = result2
    const result3 = await requestSpuImgList(props.newSpuInfo.id)
    tmImgData.value = result3
    //创建图片数据回填，需要增加关联的2个属性(回填放在获取图片数据之后，因为这里是异步请求。放外面会先执行空数据)
      tmImgData.value.forEach(item=>{
        //在类型定义中加入可选
        item.name=item.imgName,
        item.url=item.imgUrl
      })
    const result4 = await requestSpuSaleAttrList(props.newSpuInfo.id)
    salesAttrList.value = result4
    //给属性值列表加一个数据，用来控制表单显示隐藏
    salesAttrList.value.forEach(item=>{
       item.isEdit = false
       item.inputValue = ''
      })
  }
}

onMounted(() => {
  getNeedData();
})

//销售属性的下拉展示,通过计算属性可以根据添加变化而变化，这里只需要获取即可
const newSalesAttrData = computed(()=>{
 return salesAttrData.value.filter(item1=>{
        //拿出自身每一项，去属性列表中查找一一对应，如果里面没有则保留
      return salesAttrList.value.every(item2=>{
          //属性值列表中的属性名相等的时候返回false，如果不等返回true，
          return item2.saleAttrName !== item1.name
  })
})
})


let tempSalesAttr = ref('')
// console.log(tempSalesAttr,'111')
//这个数据关联了表格，点击会获取一个拼接字符串就是下拉框内容
// 创建一个需要插入到属性值列表的数据的函数，点击新增属性名逻辑
const AddNewSalesValue = ()=>{
  const [newBaseSaleAttrId,newSaleAttrName] = tempSalesAttr.value.split(":")
   const tempSalesValue={
    // 这里切割出来时string，所以+隐式转换
    baseSaleAttrId:+newBaseSaleAttrId,
    saleAttrName:newSaleAttrName,
    spuSaleAttrValueList:[]
  }

  salesAttrList.value.push(tempSalesValue)
  //没次添加完，清空临时数据
  tempSalesAttr.value = ''
}


//点击新增属性值逻辑
//创建一个input的ref值，获取元素
const InputRef = ref()
const addSalesValue = (row:SpuSaleAttrItemType)=>{
  //切换到input
  row.isEdit = true
  //让表单获取焦点
  nextTick(()=>{
    InputRef.value.focus()
  })
}

//失去焦点的逻辑
const handleInputConfirm = (row:SpuSaleAttrItemType)=>{
  //表单绑定一个值，需要用来输入添加，给属性列表增加一个属性
  let inputValue = row.inputValue 

  //判断
  // 表单失焦时如果为空
  if(!row.inputValue){
    //回到新增，并停止下一步
    row.isEdit = false
    return
  }

  //判断输入的值是否重复
  const isRepeat = row.spuSaleAttrValueList.some(item=>{
     //返回符合条件的布尔值
     return item.saleAttrValueName === inputValue
  })

  //判断是否重复
  if(isRepeat){
    ElMessage.error('你输入的值有重复')
    row.isEdit = false
    // 清空输入数据
    row.inputValue = ''
    return
  }

  //如果没有重复，则直接添加到数据中
  const newSaleAttrValue = {
    baseSaleAttrId:row.baseSaleAttrId,
    saleAttrValueName:inputValue as string
  }

  row.spuSaleAttrValueList.push(newSaleAttrValue)

  // 返回按钮
  row.isEdit = false
  //清空输入
  row.inputValue = ''
}

//save提交数据
const saveSpuData= async()=>{
  // 收集图片，自己添加的图片数据需要做修改
  const newImgList = tmImgData.value.map(item=>{
    //如果数据中有response则是自己传的数据,类型中需要加一个可选resopnes
    if(item.response){
      return {
        imgName:item.name as string,
        imgUrl:item.response.data as string
      }
    }else{
        return{
          imgName:item.name as string,
          imgUrl:item.imgUrl
        }
      }
  })

  //整理属性列表数据，去掉多余的临时条件
  salesAttrList.value.forEach(item=>{
    delete item.isEdit
    delete item.inputValue
  })
 
  // 给newSpuInfo新增修改后两个属性列表
  props.newSpuInfo.spuSaleAttrList = salesAttrList.value
  props.newSpuInfo.spuImageList = newImgList
  //发送请求
  try{
    //判断是否有id
    if(props.newSpuInfo.id){
      //如果有id则是更新
      await requestUpdateSpuInfo(props.newSpuInfo)
    }else{
      //如果没有则是新增
      await requestSaveSpuInfo(props.newSpuInfo)
    }
  }catch(e){
    ElMessage.error('保存失败')
  } 

  //保存结束返回spu列表
  emit('changeShowState',0)
}
</script>
